package com.eddie.linkedlist;

import lombok.NoArgsConstructor;

public class DoubleLinkedListDemo {

    public static void main(String[] args) {
        DoubleLinkedList doubleLinkedList = new DoubleLinkedList();
        HeroNode2 heroNode1 = new HeroNode2(1, "Eddie", "Eddie");
        HeroNode2 heroNode2 = new HeroNode2(3, "吴彦祖", "Eddie");
        HeroNode2 heroNode3 = new HeroNode2(2, "彭于晏", "Eddie");
        HeroNode2 heroNode4 = new HeroNode2(4, "胡歌", "Eddie");
        doubleLinkedList.addSort(heroNode1);
        doubleLinkedList.addSort(heroNode2);
        doubleLinkedList.addSort(heroNode3);
        doubleLinkedList.addSort(heroNode4);
        doubleLinkedList.list();


    }


}

class DoubleLinkedList {
    private HeroNode2 head = new HeroNode2(0, "", "");

    public HeroNode2 getHead() {
        return head;
    }

    /**
     * 遍历双向链表
     */
    public void list() {
        HeroNode2 temp = head.next;
        while (temp != null) {
            System.out.println(temp);
            temp = temp.next;
        }
    }

    /**
     * 默认添加到链表尾部
     */
    public void add(HeroNode2 heroNode2) {
        HeroNode2 cur = head;
        while (true) {
            if (cur.next == null) {
                heroNode2.pre = cur;
                cur.next = heroNode2;
                break;
            }
            cur = cur.next;
        }
    }

    /**
     * 按照编号顺序添加
     */
    public void addSort(HeroNode2 heroNode2) {
        HeroNode2 cur = head;
        boolean flag = false;
        while (cur.next != null) {
            if (cur.next.no == heroNode2.no) {
                flag = true;
                break;
            } else if (cur.next.no > heroNode2.no) {
                break;
            }
            cur = cur.next;
        }
        if (flag) {
            System.out.println("编号已存在");
        } else {
            heroNode2.pre = cur;
            heroNode2.next = cur.next;
            cur.next = heroNode2;
        }
    }
}

/**
 * 创建一个双向链表的类
 */
@NoArgsConstructor
class HeroNode2 {
    public int no;
    public String name;
    public String nickName;

    /**
     * 指向下一个节点
     */
    public HeroNode2 next;

    /**
     * 指向上一个节点
     */
    public HeroNode2 pre;
    //构造器

    public HeroNode2(int no, String name, String nickName) {
        this.no = no;
        this.name = name;
        this.nickName = nickName;
    }

    @Override
    public String toString() {
        return "HeroNode{" +
                "no=" + no +
                ", name='" + name + '\'' +
                ", nickName='" + nickName + '}';
    }
}
